package com.dms.modules.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dms.common.exception.BusinessException;
import com.dms.modules.admin.dto.AdminCommentAuditDTO;
import com.dms.modules.admin.dto.AdminCommentReportHandleDTO;
import com.dms.modules.admin.dto.AdminCommentRuleDTO;
import com.dms.modules.admin.dto.AdminSensitiveWordDTO;
import com.dms.modules.admin.entity.AdminCommentReport;
import com.dms.modules.admin.entity.AdminCommentRule;
import com.dms.modules.admin.entity.AdminSensitiveWord;
import com.dms.modules.admin.mapper.AdminCommentReportMapper;
import com.dms.modules.admin.mapper.AdminCommentRuleMapper;
import com.dms.modules.admin.mapper.AdminSensitiveWordMapper;
import com.dms.modules.admin.service.AdminCommentService;
import com.dms.modules.admin.vo.AdminCommentReportVO;
import com.dms.modules.product.entity.ProductComment;
import com.dms.modules.product.service.ProductCommentService;
import com.dms.modules.product.vo.CommentVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 管理员评论服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AdminCommentServiceImpl implements AdminCommentService {

    private final ProductCommentService productCommentService;
    private final AdminCommentReportMapper commentReportMapper;
    private final AdminSensitiveWordMapper sensitiveWordMapper;
    private final AdminCommentRuleMapper commentRuleMapper;

    @Override
    public IPage<CommentVO> getPendingComments(Page<CommentVO> page) {
        // 创建ProductComment的分页对象
        Page<ProductComment> commentPage = new Page<>(page.getCurrent(), page.getSize());
        
        // 查询待审核评论
        IPage<ProductComment> commentResult = productCommentService.page(
            commentPage,
            new LambdaQueryWrapper<ProductComment>()
                .eq(ProductComment::getStatus, 0)  // 0-待审核
                .orderByDesc(ProductComment::getCreateTime)
        );
        
        // 转换为CommentVO分页对象
        return commentResult.convert(comment -> {
            CommentVO vo = new CommentVO();
            BeanUtils.copyProperties(comment, vo);
            return vo;
        });
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean auditComment(Long commentId, Integer status, String remark) {
        ProductComment comment = productCommentService.getById(commentId);
        if (comment == null) {
            throw new BusinessException("评论不存在");
        }
        comment.setStatus(status);
        comment.setContent(remark);
        comment.setUpdateTime(LocalDateTime.now());
        return productCommentService.updateById(comment);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchAuditComments(AdminCommentAuditDTO dto) {
        List<ProductComment> comments = productCommentService.listByIds(dto.getCommentIds());
        if (comments.isEmpty()) {
            return false;
        }
        
        LocalDateTime now = LocalDateTime.now();
        for (ProductComment comment : comments) {
            comment.setStatus(dto.getStatus());
            comment.setContent(dto.getRemark());
            comment.setUpdateTime(now);
        }
        return productCommentService.updateBatchById(comments);
    }

    @Override
    public IPage<AdminCommentReportVO> getCommentReports(Page<AdminCommentReportVO> page) {
        return commentReportMapper.selectCommentReports(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean handleCommentReport(AdminCommentReportHandleDTO dto) {
        for (Long reportId : dto.getReportIds()) {
            AdminCommentReport report = new AdminCommentReport();
            report.setId(reportId);
            report.setStatus(1); // 已处理
            report.setHandleResult(dto.getRemark());
            report.setRemark(dto.getRemark());
            report.setHandleTime(LocalDateTime.now());
            commentReportMapper.updateById(report);
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long addSensitiveWord(AdminSensitiveWordDTO dto) {
        AdminSensitiveWord sensitiveWord = new AdminSensitiveWord();
        BeanUtils.copyProperties(dto, sensitiveWord);
        sensitiveWordMapper.insert(sensitiveWord);
        return sensitiveWord.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteSensitiveWord(Long id) {
        return sensitiveWordMapper.deleteById(id) > 0;
    }

    @Override
    public List<AdminSensitiveWordDTO> getSensitiveWords() {
        List<AdminSensitiveWord> words = sensitiveWordMapper.selectList(null);
        return words.stream()
                .map(word -> {
                    AdminSensitiveWordDTO dto = new AdminSensitiveWordDTO();
                    BeanUtils.copyProperties(word, dto);
                    return dto;
                })
                .collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long addCommentRule(AdminCommentRuleDTO dto) {
        AdminCommentRule rule = new AdminCommentRule();
        BeanUtils.copyProperties(dto, rule);
        commentRuleMapper.insert(rule);
        return rule.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateCommentRule(Long id, AdminCommentRuleDTO dto) {
        AdminCommentRule rule = new AdminCommentRule();
        BeanUtils.copyProperties(dto, rule);
        rule.setId(id);
        return commentRuleMapper.updateById(rule) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteCommentRule(Long id) {
        return commentRuleMapper.deleteById(id) > 0;
    }

    @Override
    public List<AdminCommentRuleDTO> getCommentRules() {
        List<AdminCommentRule> rules = commentRuleMapper.selectList(null);
        return rules.stream()
                .map(rule -> {
                    AdminCommentRuleDTO dto = new AdminCommentRuleDTO();
                    BeanUtils.copyProperties(rule, dto);
                    return dto;
                })
                .collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean scoreCommentQuality(Long commentId, Integer score) {
        ProductComment comment = productCommentService.getById(commentId);
        if (comment == null) {
            throw new BusinessException("评论不存在");
        }
        
        // 使用普通的UpdateWrapper更新数据库
        return productCommentService.update(
            null,
            new UpdateWrapper<ProductComment>()
                .eq("id", commentId)
                .set("quality_score", score)
                .set("update_time", LocalDateTime.now())
        );
    }
} 